#include <dirent.h>
#include "dir.h"
#include<vector>
#include<fstream>
#include<iostream>
#include<archive.h>
#include<archive_entry.h>
#include<string>

using namespace std;

CEntry* MakeEntry(const string &name);

void CDir::refresh(){
 ve.clear();
 DIR *pd=opendir(Name().c_str());
 if (NULL != pd) {
  dirent *pde = NULL;
  while(NULL != (pde = readdir(pd))){
   CEntry *pe = MakeEntry(Name() + "/" + pde->d_name);
   ve.push_back(pe);
  }
  closedir(pd);
 }
}

IDir::~IDir(){
 std::vector<CEntry*>::iterator it=ve.begin();
  while (ve.end()!=it){
   delete *it;
   it++;
  }
};


void CWikiDump::refresh(){
	fstream f;
	string s;
  cout<<"11"<<endl;	
	ve.clear();
	f.open(Name().c_str());
	while(!f.eof()){
		getline(f,s);		
		if ((s.find("<title>")!=string::npos)&&(s.find("</title>")!=string::npos)){
			s=s.erase(s.find("<title>"),7);
			s=s.erase(s.find("</title>"),8);
			CEntry *am=new CEntry (s);
			ve.push_back(am);
		}
	}
};


int CArch::refresh(){
  archive *a = archive_read_new();
  archive_read_support_format_all(a);
  archive_read_support_compression_all(a);

  int r = archive_read_open_file(a, Name().c_str(), 10240);
  if (r) {
    cerr << "не удалось открыть архив " << Name().c_str() << endl;
    cerr << "ошибка " << archive_error_string(a) << endl;
    return -1;
  }
  int i = 0;
  while (1) {
    archive_entry *header = NULL;
    r = archive_read_next_header(a, &header);
    if (ARCHIVE_EOF == r) break;
    if (ARCHIVE_OK != r) {
      cerr << "Ошибка: " << archive_error_string(a) << endl;
      if (r < ARCHIVE_WARN) 
        return -1;
	}
    CEntry *rm=new CEntry (Name() + "/" + archive_entry_pathname(header));
    ve.push_back(rm);

    //cout << "file " << archive_entry_pathname(header) << endl;
    i++; if (i >= 10) break; // чтобы не тормозило
  }

  archive_read_close(a);
	};


